/*
 *  author: ThaiNB
 */
package com.aurora.as3.client
{
	import com.aurora.as3.util.SgsByteArray;

	import flash.events.EventDispatcher;

	public class MessageFilter extends EventDispatcher
	{
		private var messageBuffer:SgsByteArray;

		public function MessageFilter()
		{
			messageBuffer=new SgsByteArray();
		}

		public function receive(buf:SgsByteArray, client:SimpleClient):void
		{
			//Stuff any new bytes into the buffer
			messageBuffer.writeBytes(buf, 0, buf.length);
			messageBuffer.position=0;

			while (messageBuffer.bytesAvailable > 2)
			{
				var payloadLength:int=messageBuffer.readShort();

				if (messageBuffer.bytesAvailable >= payloadLength)
				{
					var newMessage:SgsByteArray=new SgsByteArray();
					messageBuffer.readBytes(newMessage, 0, payloadLength);
					var event:SgsEvent=new SgsEvent(SgsEvent.RAW_MESSAGE);
					event.rawMessage=newMessage;
					dispatchEvent(event);
				}
				else
				{
					//Roll back the length we read
					messageBuffer.position-=2;
					break;
				}
			}

			var newBuffer:SgsByteArray=new SgsByteArray();
			newBuffer.writeBytes(messageBuffer, messageBuffer.position, messageBuffer.bytesAvailable);
			messageBuffer=newBuffer;
		}
	}
}